<template>
  <div id="admin-profile">
    <el-container style="height: 100vh; border: 1px solid #eee">
      <!-- 主体内容区 -->
      <el-main class="main-content">
        <!-- 头部区域 -->
        <div class="header-container">
          <el-button @click="goBack" class="back-button" size="mini">
            <i class="el-icon-arrow-left"></i> 返回
          </el-button>
          <h2 class="page-title">个人信息管理</h2>
        </div>

        <!-- 主内容卡片 -->
        <el-card class="profile-card-container">
          <!-- 查看模式 -->
          <div v-if="!isEditing" class="view-mode">
            <!-- 头像与基本信息区域 -->
            <div class="profile-header">
              <div class="avatar-wrapper">
                <img :src="userInfo.avatar || defaultAvatar" class="profile-avatar" alt="管理员头像">
                <div class="avatar-action">
                  <el-button size="mini" type="primary" @click="startEditing" icon="el-icon-camera">
                    修改头像
                  </el-button>
                </div>
              </div>

              <div class="profile-basic">
                <h3 class="profile-name">{{ userInfo.name || '未设置姓名' }}</h3>
                <p class="profile-role">
                  <span class="role-tag">{{ getRoleText(userInfo.managerType) || '未设置角色' }}</span>
                </p>
              </div>
            </div>

            <!-- 详细信息区域 - 改为横向排列 -->
            <div class="profile-details ">
              <div class="detail-item">
                <div class="detail-content">
                  <span class="detail-label">手机号码</span>
                  <div class="detail-value-wrapper">
                    <span class="detail-value">{{ userInfo.phone || '未设置' }}</span>
                    <el-button size="mini" type="text" class="edit-tag" @click="goToChange('phone')" title="修改手机号码">
                      <i class="el-icon-edit"></i>
                    </el-button>
                  </div>
                </div>
              </div>

              <div class="detail-item">
                <div class="detail-content">
                  <span class="detail-label">性别</span>
                  <span class="detail-value">{{ userInfo.gender || '未设置' }}</span>
                </div>
              </div>

              <div class="detail-item">
                <div class="detail-content">
                  <span class="detail-label">出生日期</span>
                  <span class="detail-value">{{ formatDate(userInfo.birthDate) || '未设置' }}</span>
                </div>
              </div>

              <div class="detail-item">
                <div class="detail-content">
                  <span class="detail-label">年龄</span>
                  <span class="detail-value">{{ userInfo.age || calculateAge(userInfo.birthDate) || '未设置' }}</span>
                </div>
              </div>

              <div class="detail-item">
                <div class="detail-content">
                  <span class="detail-label">所在地</span>
                  <span class="detail-value">{{ userInfo.location || '未设置' }}</span>
                </div>
              </div>
            </div>

            <!-- 操作按钮区域 -->
            <div class="action-buttons">
              <el-button type="primary" @click="startEditing" icon="el-icon-edit">
                编辑信息
              </el-button>
              <el-button type="warning" @click="goToChange('password')" icon="el-icon-key">
                修改密码
              </el-button>
              <el-button type="danger" @click="confirmLogout" icon="el-icon-logout">
                退出登录
              </el-button>
            </div>
          </div>

          <!-- 编辑模式 -->
          <div v-else class="edit-mode">
            <div class="edit-header">
              <h3 class="edit-title">编辑个人信息</h3>
              <el-button type="text" class="close-edit" @click="cancelEditing">
                <i class="el-icon-close"></i>
              </el-button>
            </div>

            <el-form :model="tempAdminInfo" ref="editForm" label-width="120px" class="edit-form" :rules="formRules">
              <el-form-item label="头像">
                <div class="avatar-upload-container">
                  <img :src="tempAdminInfo.avatar || defaultAvatar" class="preview-avatar" alt="预览头像">
                  <el-upload class="avatar-uploader" ref="uploadRef" :show-file-list="false"
                    :accept="'image/jpg,image/jpeg,image/png'" :before-upload="beforeAvatarUpload"
                    :on-change="handleAvatarChange" :action="uploadAction">
                    <el-button size="small" type="primary" icon="el-icon-upload">
                      上传头像
                    </el-button>
                  </el-upload>
                </div>
              </el-form-item>

              <el-form-item label="姓名" prop="name">
                <el-input v-model="tempAdminInfo.name" placeholder="请输入姓名"></el-input>
              </el-form-item>

              <el-form-item label="出生日期" prop="birthDate">
                <el-date-picker v-model="tempAdminInfo.birthDate" type="date" placeholder="选择出生日期" @change="updateAge"
                  style="width: 100%;">
                </el-date-picker>
              </el-form-item>

              <el-form-item label="性别" prop="gender">
                <el-select v-model="tempAdminInfo.gender" placeholder="请选择性别" style="width: 100%;">
                  <el-option label="男" value="男"></el-option>
                  <el-option label="女" value="女"></el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="所在地" prop="location">
                <local-select v-model="tempAdminInfo.location" :mode="2" @change="handleLocationChange"></local-select>
              </el-form-item>

              <el-form-item class="form-actions">
                <el-button type="primary" @click="saveChanges">保存修改</el-button>
                <el-button @click="cancelEditing">取消</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-card>
      </el-main>
    </el-container>
  </div>
</template>

<script>
// 脚本部分保持不变
import { mapGetters, mapActions } from 'vuex';
import { editBasicMessage, uploadAvatar } from '@/api/manager/manage'
import LocalSelect from '@/components/localSelect.vue';
export default {
  components: {
    LocalSelect
  },
  data() {
    return {
      defaultAvatar: 'https://picsum.photos/200/200?random=1',
      tempAdminInfo: {},
      isEditing: false,
      isLoading: false,
      uploadError: null,
      uploadAction: 'http://192.168.2.196:8080/manager/profile/uploadAvatar',
      avatarFile: null,
      tempAvatarUrl: null,

      formRules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 2, max: 20, message: '姓名长度应在2-20个字符之间', trigger: 'blur' }
        ],
        gender: [
          { required: false, message: '请选择性别', trigger: 'change' }
        ],
        location: [
          { max: 50, message: '所在地长度不能超过50个字符', trigger: 'blur' }
        ]
      }
    };
  },
  computed: {
    ...mapGetters('manager', ['userInfo', 'token']),
  },
  created() {
    if (this.token && (!this.userInfo || !this.userInfo.userId)) {
      this.fetchManagerInfo().catch(error => {
        console.error('获取管理员信息失败:', error);
      });
    }
  },
  methods: {
    ...mapActions('manager', ['fetchManagerInfo', 'logout']),
    formatDate(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'long',
        day: 'numeric'
      });
    },

    getRoleText(role) {
      const roleMap = {
        'SUPER': '超级管理员',
        'NORMAL': '普通管理员',
      };
      return roleMap[role] || role;
    },

    calculateAge(birthDate) {
      if (!birthDate) return '';

      const today = new Date();
      const birth = new Date(birthDate);
      let age = today.getFullYear() - birth.getFullYear();
      const monthDiff = today.getMonth() - birth.getMonth();

      if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birth.getDate())) {
        age--;
      }

      return age;
    },

    updateAge() {
      this.tempAdminInfo.age = this.calculateAge(this.tempAdminInfo.birthDate);
    },

    formatUTCDate(date) {
      if (!date || !(date instanceof Date) || isNaN(date.getTime())) {
        return null;
      }
      const isoString = date.toISOString();
      return isoString.replace(/\.\d{3}/, '');
    },

    startEditing() {
      this.tempAdminInfo = { ...this.userInfo };
      if (this.tempAdminInfo.birthDate) {
        this.tempAdminInfo.birthDate = new Date(this.tempAdminInfo.birthDate);
      }
      if (!this.tempAdminInfo.age && this.tempAdminInfo.birthDate) {
        this.tempAdminInfo.age = this.calculateAge(this.tempAdminInfo.birthDate);
      }
      this.isEditing = true;
    },

    cancelEditing() {
      this.isEditing = false;
      this.avatarFile = null;
      this.tempAvatarUrl = null;
    },
    
    handleLocationChange(value) {
      this.tempAdminInfo.location = value;
    },

    beforeAvatarUpload(file) {
      const isJPG = ['image/jpeg', 'image/jpg', 'image/png'].includes(file.type);
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/JPEG/PNG 格式!');
        return false;
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
        return false;
      }
      this.avatarFile = file;
      return true;
    },

    handleAvatarChange(file) {
      this.avatarFile = file.raw || file;

      const reader = new FileReader();
      reader.readAsDataURL(this.avatarFile);
      reader.onload = (e) => {
        this.tempAvatarUrl = e.target.result;
        this.tempAdminInfo.avatar = this.tempAvatarUrl;
      };
    },

    saveChanges() {
      this.$refs.editForm.validate(async (valid) => {
        if (!valid) {
          this.$message.warning('请完善表单信息');
          return;
        }
        try {
          this.isLoading = true;

          if (this.avatarFile) {
            const avatarRes = await uploadAvatar(this.avatarFile);
            if (avatarRes.data.code === 201) {
              this.tempAdminInfo.avatar = avatarRes.data.url;
              this.$store.commit('manager/SET_TOKEN', avatarRes.data.data)
            } else {
              throw new Error("头像上传失败");
            }
          }
          const data = {
            name: this.tempAdminInfo.name,
            birthDate: this.tempAdminInfo.birthDate ? this.formatUTCDate(this.tempAdminInfo.birthDate) : null,
            gender: this.tempAdminInfo.gender,
            location: this.tempAdminInfo.location,
          };
          const response = await editBasicMessage(data);
          if (response.data.code === 201) {
            const updateUserInfo = {
              ...this.userInfo,
              ...data,
            };
            this.$store.commit('manager/SET_USER_INFO', updateUserInfo);
            this.$store.commit('manager/SET_TOKEN', response.data.data);
            this.$message.success('个人信息已成功更新');
            this.isEditing = false;
          } else {
            this.$message.error(response.message || '更新信息失败');
          }
        } catch (error) {
          console.error('更新个人信息失败:', error);
          this.$message.error('网络请求失败，请稍后重试');
        } finally {
          this.isLoading = false;
        }
      });
    },

    goToChange(type) {
      this.$router.push({
        name: 'manager-change',
        query: { type }
      });
    },

    goBack() {
      this.$router.back();
    },

    confirmLogout() {
      this.$confirm('确定要退出登录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$store.commit('manager/CLEAR_STATE');
        this.$message({
          type: 'success',
          message: '已退出登录'
        });
        this.$router.push('/manage-login');
      }).catch(() => {
        // 取消退出
      });
    }
  }
};
</script>

<style scoped>
@import url('./ManagerCenterView.css');
</style>